import {
	Toast,
	removeProperty
} from '@/utils/tools.js';
import {
	Jump
} from '@/libs/fn/jump.js'
import store from '@/store/index.js'
import {
	baseURL
} from '@/common/baseconfig.js'
import {
	isEmpty,
	urlEncode
} from '@/libs/fn/verify.js'
import cookie from '@/utils/auth.js'
import {
	AESencrypt
} from "@/libs/fn/mima.js"

/**
 * @description 	以uni.request为基础封装
 * @param {string}  method		请求方式  post or get
 * @param {string}  url 		请求地址
 * @param {string}  params		参数集合	传参跟在链接后
 * @param {object}  data		data类型  传参在body内
 * @param {Boolean}  mask		是否打开 loading 默认 false
 * @param {Boolean}  toast		时候关闭Toast  类型为列表时默认不打开
 * @param {Boolean}  list 		是否是列表  主要处理列表模式下返回结果异常问题
 * @param {string}   isBase 	是否替换请求的URL
 * @param {string | Number} 	timeout 超时时间
 * @param {Object}  headers 	请求头
 * @returns {object} 
 * @example  request({
				url: '/url',
				method: "post",
				data,
				params
			})
 */
let a = '';
export async function request({
	method,
	url,
	params,
	data,
	mask = false,
	list = false,
	toast = false,
	isBase,
	timeout =
	60000,
	headers
}) {
	try {
		// if (a ==url) {
		// 	console.log('客官，太快了')
		// 	return;
		// }
		// a = url;
		// setTimeout(() => a = '', 500)

		params = removeProperty(params);
		let _url = url;
		//params传值方式  默认拼接到请求后缀
		if (!isEmpty(params)) {
			_url = `${_url}${urlEncode(params)}`
		}
		const timestamp = Math.floor(Date.now() / 1000).toString();
		const logintoken = cookie.get('Token') || '';
		const devicetoken = cookie.get('DeciceToken') || '';
		const aesStr = `${logintoken}|${devicetoken}|${timestamp}`;
		// console.log('aesStr', aesStr)
		const Authorization = `Bearer ${AESencrypt(aesStr)}`;
		let header = {
			// 'Token': cookie.get('Token'),
			'Authorization': Authorization,
			'RequestTime': timestamp,
			...headers
		};
		if (mask) {
			// 显示Loading
			// #ifdef APP-PLUS
			plus.nativeUI.showWaiting();
			// #endif
			// #ifndef APP-PLUS
			uni.showLoading({
				mask: true,
				title: '加载中'
			})
			// #endif
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: (isBase || baseURL) + _url,
				data: data,
				header: header,
				method: method,
				timeout: timeout,
				success: ({
					data,
					statusCode
				}) => {
					if (statusCode === 200) {
						const {
							success,
							msg,
							code
						} = data;
						const dataType = {
							list: [],
							pageCount: 0,
						}
						//错误时  默认打印提示
						if (!success) {
							if (toast) Toast(msg)
							resolve(data);
						}
						if (code == 'notlogin') {
							store.commit('user/REMOVE_TOKEN')
							// 非登陆页时才跳转
							let noewRoute = '';
							try {
								noewRoute = getCurrentPages()[0]['route'];
							} catch (e) {
								console.log(e)
							}
							if (noewRoute !== 'pages/login/login') {
								Jump({
									url: '/pages/login/login',
									mode: 3
								});
								Toast(msg)
							}
						}
						resolve(data);
					} else {
						errorHandler(statusCode);
						Toast(`${data.status}:${data.title}`)
						// let errData={
						// 	success:false,
						// 	msg:data.title,
						// 	code:data.status
						// }
						// reject(errData);
					}
				},
				fail: (e) => {
					errorHandler('ERR_CONNECTION_TIMED_OUT')
					return reject(e)
				},
				complete: () => {
					if (mask) {
						// 隐藏Loading
						// #ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						// #endif
						// #ifndef APP-PLUS
						uni.hideLoading();
						// #endif
					}
				}
			})
		})
	} catch (e) {
		console.log(e)
	}
}


function errorHandler(statusCode) {
	let errorCode;
	if (statusCode) {
		errorCode = statusCode
	} else {
		// errorCode = error.code;
	}
	const errorHint = {
		'ERR_CONNECTION_TIMED_OUT': '请求超时，请稍后再试',
		'request:fail timeout': '请求超时，请稍后再试',
		"ERR_NETWORK": '网络繁忙，请稍后再试',
		"ECONNABORTED": '请求超时',
		'400': '请求错误',
		'401': '未授权',
		'403': '拒绝访问',
		'404': '请求地址出错',
		'408': '请求超时',
		'500': '服务器内部错误',
		'501': '服务未实现',
		'502': '网关错误',
		'503': '服务不可用',
		'504': '网关超时',
		'505': 'HTTP版本不受支持',
	} [errorCode] || '网络繁忙,请稍后再试';
	// //错误页面
	// Jump({
	// 	url: '/pages/error',
	// 	params: {
	// 		msg: errorHint
	// 	}
	// })
	// Toast(errorHint);
}